package beer.coder.walawala.gui.hook;

import javafx.application.Platform;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

/**
 * 全局键盘事件监听.
 *
 * @author amath0312
 * @version 1.0
 * @date 2019-10-07 00:15
 */
public class GlobalKeyListener implements NativeKeyListener {

  int keyCode;
  int modifiers;
  Runnable action;

  public GlobalKeyListener(int keyCode, int modifiers, Runnable action) {
    this.keyCode = keyCode;
    this.modifiers = modifiers;
    this.action = action;
  }

  public void changeShortcut(int keyCode, int modifiers) {
    this.keyCode = keyCode;
    this.modifiers = modifiers;
  }

  @Override
  public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {
  }

  @Override
  public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
  }

  @Override
  public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {
    if (action == null) {
      return;
    }
    if (modifiers == nativeKeyEvent.getModifiers() && nativeKeyEvent.getKeyCode() == keyCode) {
      Platform.runLater(action);
    }
  }
}
